package com.mcxx.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;


public class IPUtil {

    public static String getIpAddress(HttpServletRequest request) {
        String XFor = request.getHeader("x-forwarded-for");
        if(StringUtils.isNotBlank(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {

            int index = XFor.indexOf(",");
            if(index != -1) {
                return XFor.substring(0, index);
            }
            else {
                return XFor;
            }
        }

        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("X-Real-IP");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }
}
